var Utils = require("./Utils.js");
const crypto = require('crypto');
const ConstName =require("./ConstName");
const handy = require('./handy');
const names_pre = ConstName.NAME.split("|");
const names_sub = ConstName.NAME_END.split("|");
//lBCUIA2ost7CreQZ+Z8ihF32U9sAphh68CPTEAHgRIw=
var uid = 297844432, token = "112233", port = 80, host = "tinygame.meizu.com", device = "p 7",
    imei = "112233", islogin = 1, flag = "O", icon = "", nickname = "", disconnectByMe = true, reConnectCount = 0,flymeId,online = false;
//islogin 1 已登录
var login = function (..._info) {
    if(_info && _info.length >0){
        token = _info[0][0]['token'];
        flymeId= _info[0][0]['uid'];
        imei = _info[0][1];
        device = _info[0][2];
        flag = _info[0][3];
    }
}

login.prototype.getFlag = function () {
    return flag;
}
login.prototype.getImei = function () {
    return imei;
}
login.prototype.getUid = function () {
    return uid;
}
login.prototype.getIcon = function () {
    return icon;
}
login.prototype.getNickname = function () {
    return nickname;
}
login.prototype.getOnline = function () {
    return online;
}
login.prototype.setDisConnectByMe = function (disconnectWay) {
    disconnectByMe  = disconnectWay;
}
login.prototype.reset = function () {
    port = 80, host = "tinygame.meizu.com",
    islogin = 1,icon = "", nickname = "", disconnectByMe = true, reConnectCount = 0,online = false;
}
login.prototype.queryConnector = function () {
    console.log("pomelo log4js--" + host);
    pomelo.init({
        host: host,
        port: port,
        log: false
    }, () => {
        // 连接成功之后，向gate服务器请求ip和port
        let route = "gate.gateHandler.queryEntry";
        pomelo.request(route, {
            token: token,
            imei: imei
        }, (data) => {
            console.log(data)
            host = data.host;
            port = data.port;
            // 断开与gate服务器之间的连接
            pomelo.disconnect(()=>{
            disconnectByMe = true;
            console.log("pomelo log4js--" + "主动断开链接1")
            if (data.code !== 200) {
                console.log("pomelo log4js--" + JSON.stringify(data))
            } else {
                this.entryNew();
            }
            });
            
        });
    });
}

login.prototype.entryNew = function () {
    console.log("pomelo log4js--entryNew");
    // 使用gate服务器返回的ip和port请求连接connector服务器
    pomelo.init({
        host: host,
        port: port,
        log: false,
    }, () => {
        this.entryNewDetail();
    });
}

login.prototype.entryNewDetail = function () {
    let localInfo = localStorage.getItem("loginInfo");
    let _info;
    if (!!localInfo && (_info = JSON.parse(localInfo)).isLongin) {
        token = _info.token;
        islogin = 1;
        console.log("pomelo log4js--entryNewDetail使用之前登录过的本地缓存");//头像和昵称肯定已有
        icon = _info.icon;
        nickname = _info.nickname;
    }else{
        icon = icon || `https://bro-res2.flyme.cn/resources/user-icon/${handy.randomIntRange(1, 102)}.jpg`;
        nickname = nickname || `${names_pre[handy.randomIntRange(0, names_pre.length-1)]}${names_sub[handy.randomIntRange(0, names_sub.length-1)]}`;
    }

    let route = "connector.entryHandler.enterNew";
    let now = parseInt(Date.now() / 1000);
    let param = {
        token: token,
        islogin: islogin,
        flag: flag,
        imei: imei,
        device: device,
        icon: icon ,
        nickname: nickname ,
        time: now,
        sign: crypto.createHash('md5').update("" + token + imei + now, 'utf8').digest("hex")
    };
    console.log("pomelo log4js--enterNew "+JSON.stringify(param));
    // 连接成功之后,向connector服务器发送登录请求
    pomelo.request(route, param, (data) => {
        console.log("pomelo log4js--鉴权" + JSON.stringify(data))
        if (data.code === 200) {
            pomelo.disconnect(()=>{
            disconnectByMe = true;
            console.log("pomelo log4js--" + "主动断开链接2")
            port = data.port
            host = data.host
            uid = data.uid
            token = data.token
            console.log("ppomelo log4js--enterNew success " + JSON.stringify(data))
            this.connectPomelo();
            });     
        } else {
            //登录失败，使用未登录的状态去登录，清空storage
            localStorage.removeItem("loginInfo");
            //token 过期之后继续登录下,身份不变
            islogin = 2;
            if(flag == "A" && Utils.isAndroid()) {
                new Meizu.Account().getToken( (accountMsg) =>{ 
                    console.log("onGetToken token = " + JSON.stringify(accountMsg));
                    token = accountMsg.token;
                });
            }
            // token = imei;
            if (reConnectCount++ <= 100) {
                console.log("pomelo log4js--reEnter again " + reConnectCount);
                setTimeout(() => {
                    this.entryNewDetail();
                }, 1000 + reConnectCount*100);
            } else {
                console.log("pomelo log4js--reEnter fail")
                pomelo.disconnect();
                disconnectByMe = true;
            }

        }
    });
}
// login.prototype.uid =0;

/**
   * 建立长连接的方法,断线重连可以直接调用
   * author tengqingya
   */
login.prototype.connectPomelo = function () {
    //有localstorage用localstorage，否则用上下文
    let localInfo = localStorage.getItem("loginInfo");
    console.log(localInfo);
    let _port, _host, _uid, _token,_icon,_nickname;
    let _info;
    if (!!localInfo && (_info = JSON.parse(localInfo)).isLongin) {
        _port = _info.port;
        _host = _info.host;
        _uid = _info.uid;
        _token = _info.token;
        _icon = _info.icon;
        _nickname = _info.nickname;
        console.log("pomelo log4js--从本地取用户信息");
    } else {
        _port = port;
        _host = host;
        _uid = uid;
        _token = token;
        _icon =icon;
        _nickname=nickname;
        console.log("pomelo log4js--从上下文取用户信息");
    }
    let route2 = "connector.entryHandler.enter2";
    pomelo.init({
        port: _port,
        host: _host,
        log: false,
    }, () => {
        // 连接成功之后,向connector服务器发送登录请求
        pomelo.request(route2, {
            uid: _uid,
            token: _token
        }, (data) => {
            console.log("pomelo log4js--建立连接成功" + JSON.stringify(data))
            if (data.code === 200) {
                disconnectByMe = false; //只有第一次链接成功后才需要重连
                let loginInfo = {
                    lastLoginTime: parseInt(Date.now() / 1000), isLongin: true,
                    uid: _uid,
                    token: _token,
                    port: _port,
                    host: _host,
                    flag:flag,
                    flymeId:flymeId,
                    icon:_icon,
                    nickname:_nickname
                }
                localStorage.setItem("loginInfo", JSON.stringify(loginInfo));
                reConnectCount=0;
                online= true;
                if(!Utils.isAndroid()) {
                    console.log("不是android平台，无法监听网络状态");
                    return "";
                }
                //监听下网络
                new Meizu.Device().setNetWorkListener( (msg) =>{ 
                    console.log("pomelo log4js--setNetWorkListener enable = " + JSON.stringify(msg));
                    //{"enable":true}
                    if(msg.isConnected){
                        Utils.showMzGameToast("网络恢复了");
                        console.log("pomelo log4js--网络恢复了,开始重连");
                        this.connectPomelo();
                    }
                    else{
                        console.log("pomelo log4js--断网了");
                        Utils.showMzGameToast("网络异常了");
                    }
                });
            } else {
                console.log("pomelo log4js--建立连接失败");
                pomelo.disconnect();
                disconnectByMe = true;
                localStorage.removeItem("loginInfo");
            }
        });
    });
}

pomelo.on('disconnect', (reason) => {
    online = false;
    console.log("login pomelo log4js--disconnect disconnectByMe ="+disconnectByMe)
    if (!disconnectByMe && reConnectCount++ < 100) {
        setTimeout(() => {
            console.log("login pomelo log4js--正在重连 " + reConnectCount);
            new login().connectPomelo();
        }, 1000+reConnectCount*100);
    }
});

pomelo.on('close', (reason) => {
    console.log("login pomelo log4js--on close...........reason ="+reason)
});


module.exports = login